<template>
<div class="addproduct">
    <div class="formBox">
        <h2>添加商品信息:</h2>
        <p/>
         <a-form :form="form" @submit="handleSubmit">
            <a-form-item label="分类名" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
                <a-select
                    v-decorator="[
                    'category_id',
                    { rules: [{ required: true, message: '请选择分类' }] },
                    ]"
                    placeholder="请选择分类"
                    @change="handleChange"
                    size="large"
                >
                    <a-select-option v-for="(v,k,i) in category" :key=i :value="v.id">
                    {{v.name}}
                    </a-select-option>
                </a-select>
        </a-form-item>
        <a-form-item label="商品名" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
            <a-input
                v-decorator="['name', { rules: [{ required: true, message: '请输入商品名' }] }]"
                size="large"
            />
        </a-form-item>
        <a-form-item label="内容" :label-col="{span:5}" :wrapper-col="{ span: 12 }">
            <div class="edit_container">
                <quill-editor 
                    v-model="content"
                    ref="myQuillEditor" 
                >
                </quill-editor>
             </div>  
        </a-form-item>

        <a-form-item label="排序" :label-col="{span:5}" :wrapper-col="{ span: 12 }">
            <a-input-number
                v-decorator="['sort', { rules: [{ required: true, message: '请输入排序', }] , initialValue:1}]"
                size="large"     
            ></a-input-number>
        </a-form-item>
        <a-form-item label="状态" :label-col="{ span:5 }" :wrapper-col="{ span:12 }">    
                <a-switch 
                    v-decorator="['states',{rules:[{required:true,message:'请输入状态'}] ,initialValue:true}]"
                    checkedChildren="上线"  unCheckedChildren="下线"  defaultChecked size="large"/>
        </a-form-item>
        <hr>
        <h2>添加商品标签信息:</h2>
        <p/>
        <a-table :columns="columns" :dataSource="categoryList" bordered :pagination="false" :rowKey='dataSource=>dataSource.id' v-show="categoryList.length>0">
            <template
                    v-for="col1 in ['tagName']"
                    :slot="col1"
                    slot-scope="text, record, index"
                >
                <div :key="col1">
                    <a-select
                        v-if="record.editable"
                        :value="record.tag_id"
                        @change="(e) => selectChange('categoryList',e, record.id, col1)"
                    >
                        <a-select-option v-for="(v,k) in tagsOption" :key=k :value="v.id">
                            {{v.name}}
                        </a-select-option>
                    </a-select>
                    <template v-else>{{text}}</template>
                </div>
            </template>

            <template
                     v-for="col in ['value']"
                    :slot="col"
                    slot-scope="text, record, index"
                >
                <div :key="col">
                    <a-input
                        v-if="record.editable && record.tag_id==2"
                        style="margin: -5px 0"
                        :value="text"
                        @change="e => tableChange('categoryList',e.target.value, record.id, col)"
                    />
                    <a-upload
                        v-else-if="record.editable && record.tag_id==1"
                        action="http://ll.qy.com/api/10050"
                        listType="picture-card"
                        :fileList="fileList"
                        @change="upload"
                        >
                        <div v-if="fileList.length < 1">
                            <a-icon type="plus" />
                            <div class="ant-upload-text">Upload</div>
                        </div>
                    </a-upload>
                      <a-range-picker
                        v-else-if="record.editable && record.tag_id==3"
                        @change="(e,dataString) => tableDateChange('categoryList',e,dataString, record.id, col)"
                    />
                    <template v-else-if="record.tag_id==1">
                        <img :src="getImg(text)"  height="50px">
                    </template>

                    <template v-else>{{text}}</template>
                </div>
            </template>
            <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                    <span v-if="record.editable">
                        <a @click="() => save('categoryList',record.id)">Save</a>
                        <a-popconfirm title="确认取消编辑?" @confirm="() => cancel('categoryList',record.id)">
                            <a>Cancel</a>
                        </a-popconfirm>
                    </span>
                    <span v-else>
                        <!-- ====== -->
                        <a @click="() => edit('categoryList',record.id)">Edit</a>
                        <a-popconfirm title="确认取消编辑?" @confirm="() => deleteTag('categoryList',record.id)">
                            <a>delete</a>
                        </a-popconfirm>
                    </span>
                </div>
            </template>
        </a-table>
        <div class="tagBox">
            <div class="left">
                <a-form-item
                    label="标签类型"
                    :label-col="{span:10}"
                    :wrapper-col="{span:12}"
                >
                    <a-select
                        v-model="tag_id"
                        placeholder="请选择分类"
                    >
                        <a-select-option v-for="(v,k) in tagsOption" :key=k :value="v.id">
                            {{v.name}}
                        </a-select-option>
                    </a-select>

                </a-form-item>
            </div>
            <div class="right">
                <a-form-item
                    label="标签"
                    :label-col="{span:5}"
                    :wrapper-col="{span:18}"
                >
                <a-input
                    v-show="tag_id==2?true:false"
                   v-model="tagName"
                    style="width: 60%; margin-right: 8px"
                />
                  <a-upload
                        v-show="tag_id==1?true:false"
                        action="http://ll.qy.com/api/10050"
                        listType="picture-card"
                        :fileList="fileList"
                        @change="upload"
                        >
                        <div v-if="fileList.length < 1">
                            <a-icon type="plus" />
                            <div class="ant-upload-text">Upload</div>
                        </div>
                    </a-upload>
                 <a-range-picker
                    v-model="tagTime"
                    @change="timeChange"
                    v-show="tag_id==3?true:false"
                 />
                <span class="moveright"/>
                <span class="moveright"/>
                    <a-icon
                        class="dynamic-delete-button"
                        type="plus"
                        @click="()=>add()"
                    />
                
                </a-form-item>
            </div>
        </div>
        <hr>
        
        <h2>添加商品库存:</h2><p/>

        <a-table :columns="skuColumns" :dataSource="skuList" bordered :pagination="false" :rowKey='dataSource=>dataSource.id' v-show="skuList.length>0">
            <template
                    v-for="col1 in ['original_price']"
                    :slot="col1"
                    slot-scope="text, record, index"
                >
                <div :key="col1">
                    <a-input
                        v-if="record.editable"
                        :value="record.original_price"
                        @change="e => tableChange('skuList',e.target.value, record.id, col1)"
                    />
                    <template v-else>{{text}}</template>
                </div>
            </template>

            <template
                     v-for="col2 in ['price']"
                    :slot="col2"
                    slot-scope="text, record, index"
                >
                <div :key="col2">
                    <a-input
                        v-if="record.editable"
                        :value="record.price"
                        @change="e => tableChange('skuList',e.target.value, record.id, col2)"
                    />
                    <template v-else>{{text}}</template>
                </div>
            </template>

            <template
                     v-for="col3 in ['sort']"
                    :slot="col3"
                    slot-scope="text, record, index"
                >
                <div :key="col3">
                    <a-input-number
                        v-if="record.editable"
                        :value="record.sort"
                        @change="e => tableChange('skuList',e, record.id, col3)"
                    />
                    <template v-else>{{text}}</template>
                </div>
            </template>

            <template
                     v-for="col4 in ['quantity']"
                    :slot="col4"
                    slot-scope="text, record, index"
                >
                <div :key="col4">
                    <a-input-number
                        v-if="record.editable"
                        :value="record.quantity"
                        @change="e => tableChange('skuList',e, record.id, col4)"
                    />
                    <template v-else>{{text}}</template>
                </div>
            </template>

            <template
                     v-for="col5 in ['attr']"
                    :slot="col5"
                    slot-scope="text, record, index"
                >
                <div v-for="(c,k,i) in record.attr" :key="k">
                    <a-input
                        v-if="record.editable"
                        :value="c"
                        @change="e => attrChange('skuList',e.target.value, record.id, col5,c,k)"
                    />
                    <template v-else>{{c}}</template>
                </div>
            </template>
            <template
                     v-for="col6 in ['states']"
                    :slot="col6"
                    slot-scope="text, record, index"
                >
                    <a-switch 
                        v-if="record.editable"
                        :key="col6"
                        checkedChildren="上线"  unCheckedChildren="下线"  defaultChecked size="large" 
                        :checked="text==1?true:false"
                        @click="e => tableChange('skuList',e==true?1:2, record.id, col6)"
                        />
                    <template v-else>{{text==1?"上线":"下线"}}</template>

            </template>

            <template slot="operation" slot-scope="text, record, index">
                <div class="editable-row-operations">
                    <span v-if="record.editable">
                        <a @click="() => save('skuList',record.id)">Save</a>
                        <a-popconfirm title="确认取消编辑?" @confirm="() => cancel('skuList',record.id)">
                            <a>Cancel</a>
                        </a-popconfirm>
                    </span>
                    <span v-else>
                        <a @click="() => edit('skuList',record.id)">Edit</a>
                        <a-popconfirm title="确认取消编辑?" @confirm="() => deleteTag('skuList',record.id)">
                            <a>delete</a>
                        </a-popconfirm>
                    </span>
                </div>
            </template>
        </a-table>
        <p/><p/> <p/><p/>
        <a-form :form="skuForm" @submit="skuSubmit" v-show="categoryInfo.length!=0">
            <template v-for="(i,key,index) in categoryInfo.property">
                    <a-form-item :label="i" :label-col="{ span:5 }" :wrapper-col="{ span:12 }" :key="index">    
                        <a-input 
                            v-decorator="[`attr[attr${index+1}]`, { rules: [{ required: true, message: '请输入商品标签' }] }]"
                        />
                    </a-form-item>
            </template>
            <a-form-item label="原价" :label-col="{ span:5 }" :wrapper-col="{ span:5 }">    
                <a-input 
                    v-decorator="[`original_price`, { rules: [{ required: true, message: '请输入商品原价' }] }]"
                />
            </a-form-item>
            <a-form-item label="现价" :label-col="{ span:5 }" :wrapper-col="{ span:5 }">    
                <a-input 
                    v-decorator="[`price`, { rules: [{ required: true, message: '请输入商品现价' }] }]"
                />
            </a-form-item>
            <a-form-item label="排序" :label-col="{span:5}" :wrapper-col="{ span: 12 }">
                <a-input-number
                    v-decorator="['sort', { rules: [{ required: true, message: '请输入排序', }] , initialValue:1}]"
                    size="large"     
                ></a-input-number>
            </a-form-item>
             <a-form-item label="库存" :label-col="{span:5}" :wrapper-col="{ span: 12 }">
                <a-input-number
                    v-decorator="['quantity', { rules: [{ required: true, message: '请输入库存', }] , initialValue:1}]"
                    size="large"     
                ></a-input-number>
            </a-form-item>
            <a-form-item label="状态" :label-col="{ span:5 }" :wrapper-col="{ span:12 }">    
                    <a-switch 
                        v-decorator="['states',{rules:[{required:true,message:'请输入状态'}] ,initialValue:true}]"
                        checkedChildren="上线"  unCheckedChildren="下线"  defaultChecked size="large"/>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 12, offset: 14 }">
                <a-button type="primary" html-type="submit" >
                    添加库存
                </a-button>
            </a-form-item>

        </a-form>



        <hr>
        <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
            <a-button type="primary" html-type="submit" >
                添加商品
            </a-button>
        </a-form-item>

        
    </a-form>
    </div>
  </div>
</template>

<script>
import axios from "axios";
let id=0;

export default {
     computed: {
         editor() {
                return this.$refs.myQuillEditor.quill;
        },
     },
  data() {
    // this.cacheData = this.categoryList.map(item => ({ ...item }));
    return {
        skuStates:true,
        _this:null,
        id:1,
        skuId:1,
         content: ``,
        cacheData:[],
        skuCacheData:[],
        categoryInfo:[],
        fileList:[],
        previewVisible: false,
        previewImage: '',
        columns:[
        {
            title: '标签类型',
            dataIndex: 'tagName',
            width: '15%',
            scopedSlots: { customRender: 'tagName' },

        },
        {
            title: '标签内容',
            dataIndex: 'value',
            width: '60%',
            scopedSlots: { customRender: 'value' },

        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: '25%',
            scopedSlots: { customRender: 'operation' },
        },
        ],
        
        tag_id:1,
        tagName:"",
        tagTime:[],
        categoryList:[],
        tagsOption:[
            {'id':1,'name':'图片'},
            {'id':2,'name':'宣传语'},
            {'id':3,'name':'保质期'}
        ],
      category:[],
      sort:1,
      formLayout: 'horizontal',

      skuList:[],
        skuColumns:[
        {
            title: '原价',
            dataIndex: 'original_price',
            width: '10%',
            scopedSlots: { customRender: 'original_price' },
        },
        {
            title: '现价',
            dataIndex: 'price',
            width: '10%',
            scopedSlots: { customRender: 'price' },
        },
        {
            title: '排序',
            dataIndex: 'sort',
            width: '10%',
            scopedSlots: { customRender: 'sort' },
        },
        {
            title: '库存',
            dataIndex: 'quantity',
            width: '10%',
            scopedSlots: { customRender: 'quantity' },
        },
        {
            title: '属性',
            dataIndex: 'attr',
            width: '10%',
            scopedSlots: { customRender: 'attr' },
        },
        {
            title: '状态',
            dataIndex: 'states',
            width: '10%',
            scopedSlots: { customRender: 'states' },
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: '25%',
            scopedSlots: { customRender: 'operation' },
        },
        ],
    };
  },

beforeCreate() {
    this._this = this;
    this.form = this.$form.createForm(this, { name: 'dynamic_form_item' });
    this.skuForm = this.$form.createForm(this, { name: 'sku_form_item' });
  },
  mounted(){
      this.getCategory();
  },

  methods: {
      onEditorReady(editor) { 

      },
      getImg(text){
          return "http://img.qy.com/"+text;
      },
      upload:function({ fileList }){
          this.fileList = fileList;
          this.tag_id=1;
          this.tagName=fileList[0].response;
      },
      selectChange(list,value, key, column) {
           let newData;
          if(list=="categoryList"){
              newData = [...this.categoryList];
          }else if(list=="skuList"){
              newData = [...this.skuList];
          }
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
          let tagN = "";
          for(let i=0;i<this.tagsOption.length;i++){
              if(this.tagsOption[i].id==value){
                  tagN = this.tagsOption[i].name;
              }
          }
          target[column] = tagN;
          target['tag_id'] = value;
        if(list=="categoryList"){
              this.categoryList = newData;
          }else if(list=="skuList"){
              this.skuList =newData;
          }
        }
      },
      tableChange(list,value, key, column) {
        let newData;
          if(list=="categoryList"){
              newData = [...this.categoryList];
          }else if(list=="skuList"){
              newData = [...this.skuList];
          }
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
          target[column] = value;
          if(list=="categoryList"){
              this.categoryList = newData;
          }else if(list=="skuList"){
              this.skuList =newData;
          }
        }
      },
      attrChange(list,value,key, column,c,k){
        let newData;

          if(list=="categoryList"){
              newData = [...this.categoryList];
          }else if(list=="skuList"){
              newData = [...this.skuList];
          }
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
          target[column][k] = value;
          if(list=="categoryList"){
              this.categoryList = newData;
          }else if(list=="skuList"){
              this.skuList =newData;
          }
        }
    },
      tableDateChange:function(list,value,dataString, key, column){
          let dataValue = dataString[0]+"~"+dataString[1];
           let newData;
          if(list=="categoryList"){
              newData = [...this.categoryList];
          }else if(list=="skuList"){
              newData = [...this.skuList];
          }
            const target = newData.filter(item => key === item.id)[0];
            if (target) {
            target[column] = dataValue;
             if(list=="categoryList"){
              this.categoryList = newData;
          }else if(list=="skuList"){
              this.skuList =newData;
          }
            }
      },
      edit(list,key) {
          let newData;
          if(list=="categoryList"){
              newData = [...this.categoryList];
          }else if(list=="skuList"){
              newData = [...this.skuList];
          }
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
          target.editable = true;
          if(list=="categoryList"){
             this.categoryList = newData;
          }
          else if(list="skuList"){
              this.skuList = newData;
          }
        }
      },
      deleteTag(list,id){
          if(list=="categoryList"){
            this.categoryList = this.categoryList.filter(key=>key.id!=id);
          }else if(list=="skuList"){
            this.skuList = this.skuList.filter(key=>key.id!=id);
          }
      },
      save(list,key) {
          let newData;
          if(list=="categoryList"){
              newData = [...this.categoryList];
          }else if(list=="skuList"){
              newData = [...this.skuList];
          }
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
            if(target.tag_id==1){
                target.value = this.tagName;
                this.fileList=[];
            }
          delete target.editable;
          if(list=="categoryList"){
              this.categoryList = newData;
              this.cacheData = newData.map(item => ({ ...item }));
          }else if(list=="skuList"){
              this.skuList =newData;
              this.skuCacheData = newData.map(item => ({ ...item }));
              for(let i=0;i<this.skuCacheData.length;i++){
              this.skuCacheData[i].attr = JSON.parse(JSON.stringify(this.skuCacheData[i].attr));
            }
          }
        }
      },
      cancel(list,key) {
        let newData;
          if(list=="categoryList"){
              newData = [...this.categoryList];
          }else if(list=="skuList"){
              newData = [...this.skuList];
          }
        const target = newData.filter(item => key === item.id)[0];
        if (target) {
            if(list=="category"){
                Object.assign(target, this.cacheData.filter(item => key === item.id)[0]);
            }else if(list=="skuList"){
                Object.assign(target, this.skuCacheData.filter(item => key === item.id)[0]);
                target.attr = JSON.parse(JSON.stringify(target.attr));
            }
          delete target.editable;
          if(list=="categoryList"){
              this.categoryList = newData;
          }else if(list=="skuList"){
              this.skuList = newData;
          }
        }
      },
    
      showTag:function(value){
          if(this.tagArr[value]==3){
              return true;
          }
          return false;
      },
      getCategory:function(){
                axios.get(this.GLOBAL_.apiUrl+"10004").then(
                    res=>{
                        if(res.data.code==2){
                            this.$message.error(res.data.msg);
                        }else if(res.data.code==1){
                           this.category = res.data.data;
                            // console.log(this.category);
                        }
                    }
                )
            },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
              if(this.categoryList.length==0){
                    this.$message.error("请添加商品标签信息");
                    return ;
                }
                if(this.skuList.length==0){
                    this.$message.error("请添加商品库存");
                    return ;
                }
                values.content = this.content;
                
        let params = {
            product:values,
            tags:this.categoryList,
            sku:this.skuList
        }
        console.log(params);
          axios.post(this.GLOBAL_.apiUrl+'10011',JSON.stringify(params)).then(
            res=>{
                console.log(res);
                if(res.data.code==2){
                    this.$message.error(res.data.msg);
                }else if(res.data.code==1){
                    this.$message.success(res.data.msg);
                    values = [];
                    this.restData();
                    this.skuForm.resetFields();
                    this.form.resetFields();
                    this.categoryInfo=[];
                }

            }
          )
        }
      });
    },
    restData(){
        this.categoryList=[];
        this.skuList=[];

    },
    skuSubmit(e){
        e.preventDefault();
        this.skuForm.validateFields((err, values) => {
        if (!err) {
            
            // console.log('Received values of form: ', values);
            values['id'] = this.skuId;
            this.skuList.push(values);
            this.skuCacheData = this.skuList.map(item => ({ ...item }));

            this.skuId++;
            for(let i=0;i<this.skuCacheData.length;i++){
                this.skuCacheData[i].attr = JSON.parse(JSON.stringify(this.skuCacheData[i].attr));
            }
            this.skuForm.resetFields();
        }
      });
    },
   handleChange:function(value){
               axios.get(this.GLOBAL_.apiUrl+"10005/"+value).then(
                   res=>{
                        if(res.data.code==2){
                            this.$message.error("获取分类信息失败");
                        }else if(res.data.code==1){
                            this.categoryInfo=res.data.data[0];
                            this.categoryInfo.property = JSON.parse(this.categoryInfo.property);
                        }
                   }
               )
            },
    timeChange:function(value,dataString){
        this.tagName = dataString[0]+"~"+dataString[1];
    },
    
    add:function(){
        if(this.tagName=="" || this.tagName==null){
            this.$message.error("标签内容为空");
            return;
        }
        let tagName="";
        for(let i=0;i<this.tagsOption.length;i++)
        {
            if(this.tagsOption[i].id==this.tag_id){
                tagName=this.tagsOption[i].name;
            }
        }
        let tag = {
            id:this.id,
            tag_id:this.tag_id,
            tagName:tagName,
            value:this.tagName
        }
        this.categoryList.push(tag);
        this.cacheData = this.categoryList.map(item => ({ ...item }));
        this.id++;

        this.tagName="";
        this.tag_id=1;
        this.fileList=[];

    }
  },
   
};
</script>

<style scpoed lang="less">
    .addproduct{
        width:96%;
        background:#fff;
        margin:3em auto;
        .formBox{
            width:90%;
            margin:1em auto;
            padding-top:3em;
            .tagBox{
                display:flex;
                margin-top:3em;
                .left{
                    width:20%;
                }
                .right{
                    width:80%;
                }
            }
             .icon{
                height:32px;
                display: flex;
                align-items: flex-end;
                 .anticon {
                    margin-right: 6px;
                    font-size: 32px;
                 }
                 .word{
                    color:#666;
                    font-size:24px;
                    line-height: 24px;
                    margin-left:10px;
                    display:inline-block;
                    
                 }
            }
        }
         .content{
                margin-top:1em;
                .btns{
                    width:200px;
                    margin:20px auto;
                    padding-bottom:40px;
                }
                .title{
                        font-size:16px;
                        color:#999;
                        font-weight: bold;
                    
                }
                .need{
                    color:red;
                     margin-left:10px;
                }
                .ant-input-affix-wrapper{
                    width:70%;
                    margin-left:10px;
                }
            }
            .moveright{
                    margin-left:10px;
                }
        
    }
</style>